<template>
	<div>
		<van-nav-bar title="发布新商品" />
		<div style="padding: 3vw;">
			<van-space direction="vertical" fill>
				<van-form label="新商品">
					<van-field v-model="postForm.name" label="商品标题" />
					<van-field v-model="postForm.describe" rows="5" autosize label="商品描述" type="textarea"
						placeholder="详细描述你的商品" />
					<van-field name="uploader" label="商品图片">
						<template #input>
							<van-uploader v-model="imgs" :max-count="9" />
						</template>
					</van-field>
					<van-field name="stepper" label="商品数量">
						<template #input>
							<van-stepper v-model="postForm.number" min="1" />
						</template>
					</van-field>
					<van-field v-model="priceNumber" type="number" label="价格" @update:model-value="priceChange" />

				</van-form>
				<div style="margin: 2rem;">
					<center>
						价格:
						<strong style="color: red;font-size: 2rem;margin: 0.4rem;">
							{{priceShow}} ￥
						</strong>
						
					</center>
					

				</div>

				<van-button @click="addNewGood" icon="back-top" type="success" round block>发布商品</van-button>
			</van-space>
		</div>
	</div>
</template>

<script>
	import {
		showNotify
	} from 'vant';
	import url from '@/assets/url.json';

	export default {
		props: {
			close: Function
		},
		data() {
			return {
				postForm: {
					name: '',
					number: 1,
					price: 0,
					describe: ''
				},
				imgs: [],
				priceNumber: 0,
				priceShow: '',
			}
		},

		methods: {
			addNewGood() {
				let formData = new FormData();
				if (this.imgs.length < 1) {
					showNotify({
						type: 'danger',
						message: "至少有一张图片"
					});
					return;
				}
				for (let key in this.imgs) {
					formData.append('img', this.imgs[key].file);
				}
				for (let key in this.postForm) {
					formData.append(key, this.postForm[key]);
				}
				// formData.append('id',this.$cookies.get('userId'));
				this.$axios({
					url: url.ip + '/api-goods' + '/goods/addGoods',
					method: 'POST',
					data: formData,
					headers: {
						token: this.$cookies.get('token'),
						'Content-Type': 'multipart/form-data',
					}
				}).then((res) => {
					if (res.data.code !== 0) {
						console.log(res);
						showNotify({
							type: 'danger',
							message: res.data.message
						});
					} else {
						showNotify({
							type: 'success',
							message: '发布商品成功'
						});
						this.close();
					}
				}).catch((err) => {
					console.log(err);
					showNotify({
						type: 'danger',
						message: "网络错误或用户未登录"
					});
				})

			},
			priceChange(str) {
				if (str === '') {
					this.price = 0;
					this.priceShow = '0';
					this.postForm.price = '0';
				} else {
					this.priceShow = Number.parseFloat(str).toFixed(2);
					this.postForm.price = (this.priceShow + '').replace('.', '');
				}
			}
		}
	}
</script>

<style>
</style>